import {
  getMe,
  getUserStatistics,
  getUserFollowersNum,
  getUserFansLen,
} from '@/api/user.js'

let userInfo = {} // 用户信息

/**
 * 获取用户token
 */
export function getToken() {
  return uni.getStorageSync('token') || null
}

/**
 * 设置用户token
 * @param {String} token
 */
export function setToken(token) {
  uni.setStorageSync('token', token)
}

/**
 * 清除token
 */
export function removeToken() {
  uni.removeStorageSync('token')
}

/**
 * 获取用户信息
 */
export function getUserInfo() {
  return JSON.parse(JSON.stringify(userInfo))
}
/**
 * 设置用户信息
 * @param {Object} info
 */
export function setUserInfo(info) {
  userInfo = {
    ...userInfo,
    ...info
  }
  return userInfo
}

/**
 * 加载个人信息
 * @param {Boolean} hold 请求配置文件
 */
export function getMeInfo(hold = false) {
  return getMe(hold)
    .then(res => {
      console.log(res)
      setUserInfo(res)
      return res
    })
}

/**
 * 设置个人统计信息
 * @param {Number} userId
 */
export async function getUserStatistic(userId = userInfo.userInfo.userId) {
  try {
    const [statistic, followerLen, fanLen] = await Promise.all([
      getUserStatistics(userId),
      getUserFollowersNum(userId),
      getUserFansLen(userId),
    ])

    return {
      ...statistic,
      followerLen,
      fanLen,
    }
  } catch (err) {
    return Promise.reject(err)
  }
}
